package com.itheima.reggie.web.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.service.ShoppingCartService;
import com.itheima.reggie.utils.ThreadLocalUtil;
import com.itheima.reggie.web.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 购物车控制层
 *
 * @Name : ShoppingCartController
 * @Author : WuQiang
 * @Date : 2022-08-19 20:06
 * @Description : 购物车控制层
 */
@Slf4j
@RestController
@RequestMapping("/shoppingCart")
public class ShoppingCartController {

    @Autowired
    private ShoppingCartService shoppingCartService;

    /**
     * 获取当前用户的购物车
     *
     * @return
     */
    @GetMapping("/list")
    public R list() {
        //获取当前用户id
        Long userId = ThreadLocalUtil.getCurrentId();
        List<ShoppingCart> shoppingCartList = shoppingCartService.list(Wrappers.lambdaQuery(ShoppingCart.class)
                .eq(userId != null, ShoppingCart::getUserId, userId)
                .orderByDesc(ShoppingCart::getCreateTime));
        return R.success("查询购物车列表成功", shoppingCartList);
    }

    /**
     * 添加购物车
     *
     * @param shoppingCart
     * @return
     */
    @PostMapping("/add")
    public R add(@RequestBody ShoppingCart shoppingCart) {
        return shoppingCartService.add(shoppingCart);

    }

    /**
     * 清空购物车
     *
     * @return
     */
    @DeleteMapping("/clean")
    public R clean() {
        Long userId = ThreadLocalUtil.getCurrentId();
        //通过用户id清空购物车
        boolean result = shoppingCartService.remove(Wrappers.lambdaQuery(ShoppingCart.class)
                .eq(ShoppingCart::getUserId, userId));
        if (result) {
            return R.success("清空购物车成功");
        }
        return R.error("清空购物车失败");
    }

    @PostMapping("/sub")
    public R subtract(@RequestBody ShoppingCart shoppingCart) {
        //获取当前菜品id
        Long dishId = shoppingCart.getDishId();

        boolean result = shoppingCartService.update(Wrappers.lambdaUpdate(ShoppingCart.class)
                .setSql("number = number - 1")
                .eq(ShoppingCart::getDishId, dishId));
        //查询数量  如果为0 从购物车删除该商品
        ShoppingCart cart = shoppingCartService.getOne(Wrappers.lambdaQuery(ShoppingCart.class)
                .eq(ShoppingCart::getDishId, dishId));

        if (0 == cart.getNumber()) {
            result = shoppingCartService.remove(Wrappers.lambdaQuery(ShoppingCart.class)
                    .eq(ShoppingCart::getDishId, dishId));
        }
        if (result) {
            return R.success("数量减1成功", cart);
        }
        return R.error("失败");
    }

}
